package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.excel.RiskDailyStockRepoExec;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.excel.RiskDailyStockRepoExecRepo;
import com.glsc.ngateway.opmanage.service.report.excel.ExcelUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: qiyr
 * @date: 2022/4/25 15:15
 * @description: 风险监测-股票质押回购每日信息（行权融资）导入监听器
 */
public class RiskDailyStockRepoExecListener extends AnalysisEventListener<RiskDailyStockRepoExec> {

    private static final Logger logger = LoggerFactory.getLogger(ExcelUploadService.class);
    private static final int BATCH_COUNT = 3000;
    List<RiskDailyStockRepoExec> list = new ArrayList<RiskDailyStockRepoExec>();

    private RiskDailyStockRepoExecRepo riskDailyStockRepoExecRepo;
    private String name;
    private Date date;

    public RiskDailyStockRepoExecListener() {
    }

    public RiskDailyStockRepoExecListener(RiskDailyStockRepoExecRepo riskDailyStockRepoExecRepo, String name, Date date) {
        this.riskDailyStockRepoExecRepo = riskDailyStockRepoExecRepo;
        this.name = name;
        this.date = date;
    }

    @Override
    public void invoke(RiskDailyStockRepoExec data, AnalysisContext context) {
        // 发现存在脏数据，过滤
        // 过滤条件为：业务日期为空的数据
        if (null == data.getBizDate()) {
            return;
        }

        // 用行序号当id
        data.setId(context.readRowHolder().getRowIndex());
        data.setDate(date);
        String market= riskDailyStockRepoExecRepo.getMarket(data.getSecucode());
        if(market != null){
            if(market.equals("SSE")){
                data.setMarket("上交所");
            }else if(market.equals("SZSE")){
                data.setMarket("深交所");
            }
        }
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        riskDailyStockRepoExecRepo.saveAll(list);
    }
}
